#include "eventservice.h"
#include "network/networkmanager.h"
#include "event/abstractevent.h"
#include "event/messageevent.h"
#include "parser/abstractparser.h"
#include "parser/recentcontactparser.h"
#include "parser/messageparser.h"
#include "parser/createnewgroupparser.h"
#include "account/accountuser.h"
#include "appchat/accountmanager.h"


#include <QDebug>


namespace Service {

EventService *EventService::m_instance = NULL;

EventService::EventService(QObject *parent) :
    QObject(parent)
{
    init();
}


EventService *EventService::instance(QObject *parent)
{
    if (m_instance == NULL)
        m_instance = new EventService(parent);
    return m_instance;
}


void EventService::init()
{
    registerParser(new MessageParser(this));
    registerParser(new RecentContactParser(this));
    registerParser(new CreateNewGroupParser(this));
    setConnection();
}


void EventService::setConnection() const
{
    connect(Network::Manager::instance(), &Network::Manager::received,
            this, &EventService::onReceived);
}


void EventService::onReceived(const QString &commandId, const QVariant &data)
{
    AbstractEvent *event = parseEvent(commandId, data);
    if (event == NULL)
        return;

    event->process();
    delete event;
}


AbstractEvent *EventService::parseEvent(const QString &commandId, const QVariant &data)
{
    foreach (AbstractParser *parser, m_parserList) {
        AbstractEvent *event = parser->parse(commandId, data);
        if (event != NULL) {
            return event;
        }
    }
    return NULL;
}


void EventService::registerParser(AbstractParser *parser)
{
    if (m_parserList.contains(parser))
        return;

    foreach (AbstractParser *item, m_parserList) {
        if (item->type() == parser->type()) {
            if (item != parser) {
                delete parser;
                parser = 0;
            }
            return;
        }
    }
    m_parserList.append(parser);
}


void EventService::unregisterParser(AbstractParser *parser)
{
    m_parserList.removeAll(parser);
}


void EventService::deleteParserList()
{
    qDeleteAll(m_parserList);
    m_parserList.clear();
}

} // namespace
